﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Senparc.Weixin.MP;
using Senparc.Weixin.MP.Entities;
using Senparc.Weixin.MP.MessageHandlers;


namespace NetWing.BPM.Admin.weixin
{
    /// <summary>
    /// wx 的摘要说明
    /// </summary>
    public class wx : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            


            string signature = context.Request["signature"];
            string timestamp = context.Request["timestamp"];
            string nonce = context.Request["nonce"];
            string echostr = context.Request["echostr"];
            string Token=NetWing.Common.ConfigHelper.GetValue("Token");
            string appid = NetWing.Common.ConfigHelper.GetValue("AppID");
            if (context.Request.HttpMethod == "GET")
            {
                //get method - 仅在微信后台填写URL验证时触发
                if (CheckSignature.Check(signature, timestamp, nonce, Token))
                {
                    WriteContent(echostr,context); //返回随机字符串则表示验证通过
                }
                else
                {
                    WriteContent("failed:" + signature + "," + CheckSignature.GetSignature(timestamp, nonce, Token),context);
                }

            }
            else
            {
                //判断Post或其他方式请求
                if (!Senparc.Weixin.MP.CheckSignature.Check(signature, timestamp, nonce, Token))
                {
                    WriteContent("参数错误！",context);


                    return;
                }

                //post method - 当有用户想公众账号发送消息时触发
                var postModel = new Senparc.Weixin.MP.Entities.Request.PostModel()
                {
                    Signature = context.Request.QueryString["signature"],
                    Msg_Signature = context.Request.QueryString["msg_signature"],
                    Timestamp = context.Request.QueryString["timestamp"],
                    Nonce = context.Request.QueryString["nonce"],
                    //以下保密信息不会（不应该）在网络上传播，请注意
                    Token = Token,
                    //EncodingAESKey = model.aeskey, //根据自己后台的设置保持一致
                    AppId = appid //根据自己后台的设置保持一致
                };

                //v4.2.2之后的版本，可以设置每个人上下文消息储存的最大数量，防止内存占用过多，如果该参数小于等于0，则不限制
                //v4.2.2之后的版本，可以设置每个人上下文消息储存的最大数量，防止内存占用过多，如果该参数小于等于0，则不限制
                var maxRecordCount = 0;


            }

            context.Response.End();
        }
        

        private void WriteContent(string str, HttpContext context)
        {
            context.Response.Output.Write(str);
        }






        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}